<template>
    <el-dialog
            :visible.sync="visible"
            width="700px"
            :before-close="handleClose"
            class="box-card">
        <div class="title">
            <i class="el-icon-edit"> {{ title }}</i>
        </div>
        <br>
        <el-form
                v-loading="loading"
                ref="formRef"
                :rules="rules"
                :model="formData"
                label-width="100px"
                label-position="right"
                style="width: 90%"
                status-icon>
            <el-form-item label="标题" prop="title">
                <el-input v-model.trim="formData.title" maxlength="30" clearable show-word-limit/>
            </el-form-item>
            <el-form-item label="轮播图" prop="imageUrl">
                <el-upload
                        class="avatar-uploader"
                        action="/admin/image/loop"
                        :show-file-list="false"
                        :on-success="uploadSuccess"
                        :before-upload="beforeUpload">
                    <img fit="cover" v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar"/>
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="目标网址" prop="targetUrl">
                <el-input v-model.trim="formData.targetUrl" maxlength="100" clearable show-word-limit/>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model.trim="formData.sort" :min="1" :max="1000">
                </el-input-number>
            </el-form-item>
            <el-form-item label="状态" prop="state">
                <el-select v-model.trim="formData.state" clearable style="width:185px">
                    <el-option label="正常" value="1"></el-option>
                    <el-option label="不可用" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item align="right">
                <el-button @click="handleClose" size="mini">取消</el-button>
                <el-button @click="resetForm('formRef')" size="mini">重置</el-button>
                <el-button type="primary" @click="submitForm('formRef')" size="mini">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
    import {addLoop, updateLoop} from '@/api/api'

    export default {
        props: {
            title: { // 弹窗的标题
                type: String,
                default: ''
            },
            visible: { // 弹出窗口，true弹出
                type: Boolean,
                default: false
            },
            formData: { // 提交表单数据对象
                type: Object,
                default: () => { // 对象或数组默认值必须从一个工厂函数获取
                    return {}
                }
            },
            remoteClose: Function // 用于关闭窗口
        },
        data() {
            return {
                loading: false,
                oldImageUrl: String, // 编辑时，查询出来的那张图片地址
                // 校验表单数据
                rules: {
                    title: [
                        {required: true, message: '轮播图标题不能为空', trigger: 'blur'},
                        {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
                    ],
                    imageUrl: [
                        {required: true, message: '图片不能为空', trigger: 'blur'},
                        {
                            // eslint-disable-next-line no-useless-escape
                            pattern: /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
                            message: '链接地址格式不正确',
                            trigger: 'blur'
                        }
                    ],
                    targetUrl: [
                        {required: true, message: '跳转网址不能为空', trigger: 'blur'},
                        {
                            // eslint-disable-next-line no-useless-escape
                            pattern: /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
                            message: '链接地址格式不正确',
                            trigger: 'blur'
                        }
                    ]
                }
            }
        },
        methods: {
            // 取消(关闭窗口,清空表单和校验结果)
            handleClose() {
                this.$refs['formRef'].resetFields()
                // 注意不可以通过  this.visible = false来关闭，因为它是父组件的属性
                this.remoteClose()
            },
            // 重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields()
            },
            // 上传图片之前
            beforeUpload(file) {
                // const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                }
                return isLt2M;
            },
            // 上传图片成功
            uploadSuccess(response) {
                this.loading = true
                if (response.code === 20000) {
                    // 回显图片
                    // /admin/image/1638862186630_80a99312a8b84f938af5204bee961b32.png
                    this.formData.imageUrl = this.blog_constant.baseUrl + '/admin/image/' + response.data.id;
                    // this.formData.imageUrl = this.blog_constant.baseUrl + '/admin/image/' + response.data.id;
                    this.loading = false
                    this.$message.success(response.message)
                } else {
                    this.$message.error(response.message)
                }
            },
            // 提交表单数据
            submitForm(formRef) {
                this.$refs[formRef].validate((valid) => {
                    if (valid) {
                        // 校验通过，提交表单数据
                        this.addOrUpdate()
                    } else {
                        return false
                    }
                })
            },
            // 添加或更新
            // 添加或更新
            async addOrUpdate() {
                let response = null
                // 有 id 为更新
                if (this.formData.id) {
                    response = await updateLoop(this.formData)
                    if (response.code === 20000) {
                        this.$message.success(response.message)
                        // 关闭窗口
                        this.handleClose()
                    } else {
                        this.$message.error(response.message)
                    }
                } else {
                    // 没 id 为添加
                    response = await addLoop(this.formData)
                    if (response.code === 20000) {
                        this.$message.success(response.message)
                        // 关闭窗口
                        this.handleClose()
                    } else {
                        this.$message.error(response.message)
                    }
                }
            }


        }
    }
</script>
<style>
    .title {
        font-size: 22px;
        text-align: center;
        margin-bottom: 20px;
    }

    /* 上传组件的样式 */
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>